const connection = require("../app/database");
const { to } = require("../utils");

class LabelService {
    async create(name, id) {
        const statement = `INSERT INTO label (name,user_id) VALUES (?,?)`;
        const [error, resp] = await to(connection.execute(statement, [name, id]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async list() {
        const statement = `SELECT 
        l.name name, l.createAt createTime, l.updateAt updateTime,
        JSON_OBJECT('id',u.id,'name',u.name) AS createdUser
        FROM label l
        LEFT JOIN user u on l.user_id = u.id`;
        const [error, resp] = await to(connection.execute(statement));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async findLabelByName(name) {
        const statement = `SELECT * FROM label WHERE name = ?`;
        const [error, resp] = await to(connection.execute(statement, [name]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result[0];
    }

    async removeLabelById(id) {
        const statement = `DELETE FROM label WHERE id = ?`;
        const [error, resp] = await to(connection.execute(statement, [id]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }
}

module.exports = new LabelService();
